package demo.Socket_learn.ManyTcpClent;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/16-08-16-14:31
 * @Description：demo.Socket_learn.ManyTcpClent
 */
public class Server_Thread {
    public static void main(String[] args) {
        ServerSocket server = null;
        Socket accept = null;

        try {
            server = new ServerSocket(6666);
            System.out.println("服务端启动，等待客户端连接，，，，");
            while(true) {
                accept = server.accept();
                System.out.println(accept);
                new SocketThread(accept).start();
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
class SocketThread extends Thread{
    private Socket accept = null;
    PrintWriter writer = null;
    BufferedReader reader1 = null;
    BufferedReader reader2 = null;
    public SocketThread(Socket accept) {
        this.accept =accept;
    }

    @Override
    public void run() {
        try {
            //接收数据
            //read 是一个阻塞流，等待对方写数据
            writer = new PrintWriter(new OutputStreamWriter(accept.getOutputStream()));
            reader1 = new BufferedReader(new InputStreamReader(accept.getInputStream(), "utf-8"));
            reader2 = new BufferedReader(new InputStreamReader(System.in));
            String str;
            while (true) {
                str = reader1.readLine();
                System.out.println("客户端： " + str);
                System.out.flush();

                str = reader2.readLine();

                //服务端回写数据
                writer.println(str);
                writer.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (accept != null) {
                    accept.close();
                }
                if (writer != null) {
                    writer.close();
                }
                if (reader1 != null) {
                    reader1.close();
                }
                if (reader2 != null) {
                    reader2.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
